package gods.bubble.search;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.wltea.analyzer.lucene.IKQueryParser;

public class QueryLogicParser {
	public static BooleanQuery logicalParse(String query, int type)
			throws IOException {
		String[] words = query.split("\\s+");

		ArrayList<String> shoulds = new ArrayList<String>();
		ArrayList<String> nots = new ArrayList<String>();

		for (String word : words) {
			if (word.startsWith("-")) {
				nots.add(word.replaceAll("-", ""));
			} else {
				shoulds.add(word);
			}
		}

		StringBuilder output = new StringBuilder();

		output.append("QueryLogicParser:\n");
		output.append("Get SHOULD: ");

		if (shoulds.isEmpty()) {
			return null;
		}

		for (String word : shoulds) {
			output.append(word + " + ");
		}

		output.append("\n");

		if (!nots.isEmpty()) {
			output.append("Get NOT: ");

			for (String word : nots) {
				output.append(word + " + ");
			}

			output.append("\n");
		}

		System.out.println(output.toString());

		BooleanQuery bq = new BooleanQuery();

		if (type != Searcher.Type.SCHOLAR) {
			for (String word : shoulds) {
				Query q = IKQueryParser.parse("title", word);
				bq.add(q, Occur.SHOULD);
	
				q = IKQueryParser.parse("content", word);
				bq.add(q, Occur.SHOULD);
			}
	
			for (String word : nots) {
				Query q = IKQueryParser.parse("title", word);
				bq.add(q, Occur.MUST_NOT);
	
				q = IKQueryParser.parse("content", word);
				bq.add(q, Occur.MUST_NOT);
			}
	
			if (type == Searcher.Type.NEWS) {
				Query q = IKQueryParser.parse("url", "news");
				bq.add(q, Occur.MUST);
			}
		}
		else {
			for (String word : shoulds) {
				Query q = IKQueryParser.parse("title", word);
				bq.add(q, Occur.SHOULD);
			}
	
			for (String word : nots) {
				Query q = IKQueryParser.parse("title", word);
				bq.add(q, Occur.MUST_NOT);
			}
		}

		return bq;
	}

	public static void main(String args[]) throws IOException {
		QueryLogicParser.logicalParse("计算机", 0);
	}
}
